import React from 'react';
import { Button as AButton } from 'antd';
import { ButtonProps as AButtonProps } from 'antd/lib/button';
import Qs from 'query-string';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { ActionFieldType, CanvasItemProps, EventsType } from './../../interface';
import evalScriptText from './../../eval';
import { ShowModalOptionsType } from './../../interface';
import styles from './button.module.scss';

export interface ButtonProps extends CanvasItemProps {
  buttonProps: AButtonProps & {
    scriptText?: string;
    text?: string;
    textEn?: string;
    classType?: string;
    noCheckRequired?: boolean; // 是否校验必填
  };
  disabled?: boolean;
  onValuesChange(id: string, data: any, isButtonChange: boolean): void;
  validateRequired(): void;
  showMessage(optiona: any): void;
  Events?: EventsType,
  enviromentConfig?: any;
  business?: any;
}

const Button = (props: ButtonProps) => {
  const query = Qs.parseUrl(window.location.href).query;
  const { enviromentConfig, domComplete, disabled, buttonProps: _buttonProps, validateFields, onValuesChange, controlRefs, setActionFiledMap, ...canvasProps } = props;
  const { scriptText, ...buttonProps } = _buttonProps;

  useQueryControlWrap(canvasProps.id, '', domComplete);

  async function onClick() {
    if (validateFields && scriptText) {
      const values = await validateFields(typeof _buttonProps.noCheckRequired === 'boolean' ? !_buttonProps.noCheckRequired : true);

      const refsKey = Object.keys(controlRefs as any);
      const refDataList: any = [];

      if (refsKey.length) {
        for (let item of refsKey) {
          if (controlRefs?.[item]?.onListRefresh) {
            refDataList.push(controlRefs?.[item]);
          }
          refDataList[item] = controlRefs?.[item];
        }
      }

      evalScriptText({
        scriptText,
        extra: {
          _OBJ1_: values,
          _REFS_: refDataList,
          _QUERY_: query,
          _ENV_: enviromentConfig || {},
          _EVENTS_: props.Events,
          _BUSINESS_: props.business,
          showModal: (options: ShowModalOptionsType) => props.showModal?.(options, props._id),
          showMessage: props.showMessage,
          parentNext: props.parentNext,
          validateRequired: props.validateRequired
        },
        next: (result: any, actionFiled?: ActionFieldType) => {
          onValuesChange((props._id || props.id)!, result || {}, true);

          if (actionFiled) {
            setActionFiledMap?.((prev: ActionFieldType) => {
              return { ...prev, ...actionFiled };
            });
          }
        }
      });
    }
  }

  return !disabled ? (
    <div {...canvasProps} className={styles.button}>
      <AButton {...buttonProps} onClick={onClick} disabled={disabled}>
        {(localStorage.i18nextLng === 'en' ? props.buttonProps?.textEn : props.buttonProps?.text) || props.buttonProps?.text}
      </AButton>
    </div>
  ) : null;
};

export default Button;